import os

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

import django
from django import http
from django import shortcuts

from sendemail.models import *
from sendemail.helper import *
from sendemail.sql import *
from sendemail.sessions import *
from conf.settings import *
 

def dashboard(request):
    params = {}
    vemails = VEmail.all()
    params['total_email'] = vemails.count()
    vemailsSent = VEmail.gql("WHERE status=1")
    params['total_sent'] = vemailsSent.count()
    vemailsNoSent = VEmail.gql("WHERE status=0")
    params['total_nosent'] = vemailsNoSent.count()
    vemailsNoUnique = VEmail.gql("WHERE status=2")
    params['total_nouniquie'] = vemailsNoUnique.count()
    vEmailContent = VEmailContent.gql("WHERE status=1 LIMIT 1").get()
    if vEmailContent:
        params['content'] = vEmailContent
  
    params['auto_send'] = getConfig('auto_send')
    params['Title'] = 'Dash Board'
    params['items'] = vemails
    
    return respond(request, None, 'vemail_dashboard', params)

def list(request):
  params = {}
  vemails = VEmail.all()
  p = int(SafeGet('page', 0, request)) + 1
  StringPaging = paging(vemails.count(), '?page=', PAGE_SIZE, p)
  
  vemails = vemails.fetch(PAGE_SIZE, ((p - 1) * PAGE_SIZE))
 
  params['Title'] = 'List Email'
  params['items'] = vemails
  params['StringPaging'] = StringPaging
  
  return respond(request, None, 'vemail_list', params)

def delall(request):
  params = {}
  status = SafeGet('status', None, request)
  if status is None:
      sql = "LIMIT 200"
  else:
      sql = "WHERE status=" + status + " LIMIT 200"
   
  vemails = VEmail.gql(sql)
  if vemails.count() > 0:
      db.delete(vemails)
  vemails = VEmail.gql(sql)
  if vemails.count() > 0:
      return respond(request, None, 'vemail_delall', params)  
  else:
      return respond(request, None, 'message_box', {"message":"Delete All."})
  
def refesh(request):
  params = {}
  params['Title'] = 'Refesh All Emails'
  sql = "WHERE status=1 LIMIT 200"
  vemails = VEmail.gql(sql)
  for item in vemails:
      item.status = 0
      item.put()
  vemails = VEmail.gql(sql)    
  if vemails.count() > 0:
      return respond(request, None, 'vemail_refesh', params)  
  else:
      return respond(request, None, 'message_box', {"message":"Refesh All Emails."})
  
  

def uniqueemail(request):
    params = {}
    params['duplicate'] = ''
    params['result'] = ''
    sql = "WHERE status = 2 LIMIT 10"
    vEmails = VEmail.gql(sql)
    for vEmail in vEmails:
        #validatte
        vEmailValidate = VEmailValidate()
        vEmailValidate.name = vEmail.name
        vEmailValidate.status = 0 # Not sent
        vEmailValidate.put()
        
        count = CountVEmail(vEmail.name)
        if count > 1:
            params['duplicate'] += vEmail.name + "; "
            vEmail.delete()
        else:
            vEmail.status = 0 # Not validate unique
            vEmail.put()
            params['result'] += vEmail.name + "; "

    vEmails = VEmail.gql(sql)    
    if vEmails.count() > 0:
        return respond(request, None, 'vemail_unique', params)
    else:
        return respond(request, None, 'message_box', {"message":"Unique All Emails."})
    

def importfile(request):
    params = {}
    params['err'] = ''
    params['duplicate'] = 'Not validate. Please use unique email or auto unique'
    params['result'] = ''

    emails = SafePost('emails', '', request)
    if emails == '':
        if not request.FILES:
            return respond(request, None, 'vemail_importfile', params)
        file = request.FILES['file']
        emails = file['content']  
    
    response_text = ''
    split = SafePost('split', '1', request)
    if split == '1':
        emails = emails.split(';')
    else:
        emails = emails.split('\n')

    for email in emails:
        email = email.strip()
        vEmail = VEmail()
        try:
            if ValidateEmail(email):
                vEmail.name = db.Email(email)
                vEmail.status = 2 # Not validate unique
                vEmail.put()
                response_text += email + "; "
            else:
                params['err'] += email + "; "
        except db.Error, err:
            params['err'] += str(err) + "; "

    params['result'] = response_text
    return respond(request, None, 'vemail_importfile', params)

